<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<%
	String bathPath = request.getContextPath();
	pageContext.setAttribute("bathPath", bathPath);
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>角色管理</title>
<jsp:include page="../common/common.jsp"></jsp:include>
<link rel="stylesheet" type="text/css" href="${bathPath}/css/tableadd/style.css" /> 
<script src="${bathPath}/js/quickui/libs/js/table/quiGrid.js" type="text/javascript"></script>
<script type="text/javascript" src="${bathPath}/js/jquery-1.9.1.min.js" ></script>
<link rel="stylesheet" href="${bathPath}/frame/layui/css/layui.css"  media="all">
<!-- mmGrid -->
<link rel="stylesheet" type="text/css" href="${bathPath}/js/mmGrid/mmGrid.css"/>
<script type="text/javascript" src="${bathPath}/js/mmGrid/mmGrid.js" ></script>
<!-- mmGrid page -->
<link rel="stylesheet" type="text/css" href="${bathPath}/js/mmGrid/mmPaginator.css"/>
<script type="text/javascript" src="${bathPath}/js/mmGrid/mmPaginator.js" ></script>

<%-- <link type="text/css" rel="stylesheet" href="${bathPath}/css/page.css"/> --%>
<script type="text/javascript" src="${bathPath}/js/ajaxSessionOut.js" ></script>
<link rel="stylesheet" type="text/css" href="${bathPath}/js/zTree_v3.5.15/css/zTreeStyle/zTreeStyle.css"/>

<!--树组件start -->
<script type="text/javascript" src="${bathPath}/js/quickui/libs/js/tree/ztree/ztree.js"></script>
<link href="${bathPath}/js/quickui/libs/js/tree/ztree/ztree.css" rel="stylesheet" type="text/css"/> 
<link href="${bathPath}/js/quickui/libs/skins/blue/style.css" rel="stylesheet" type="text/css"/> 
<!--树组件end -->
<!-- layer -->
<link type="text/css" rel="stylesheet" href="${bathPath}/js/layer/skin/layer.css"/>
<script type="text/javascript" src="${bathPath}/js/layer/layer.js" ></script>
<script type="text/javascript" src="${bathPath}/js/quickui/libs/js/popup/drag.js"></script>
<script type="text/javascript" src="${bathPath}/js/quickui/libs/js/popup/dialog.js"></script>
<style type="text/css">


.png_table{margin-bottom:8px;}

.button_a{cursor:pointer;border:1px solid #AAAAAA;padding:3px 12px 3px 12px;text-decoration:none;
	-moz-border-radius: 10px;      /* Gecko browsers */
    -webkit-border-radius: 10px;   /* Webkit browsers */
    border-radius:10px;            /* W3C syntax */
    margin-right:10px;
    text-decoration:none;
}
.button_a:HOVER{background-color:#EEEEEE;}
.button_a img{height:16px;vertical-align:-2px;border:0px;}
.button_a span{line-height:30px;font-size:14px;color:#111111;font-family::Microsoft YaHei;}

.tree_table{border:1px solid #666666;width:100%;}
.tree_table .left_tree{border-right:1px solid #666666;width:180px;}

.tab_span{font-size:13px;color:#111111;font-family::Microsoft YaHei;padding:7px 15px;border:1px solid #666666;margin-left:50px;cursor:pointer;border-bottom:none;}
.tab_span_checked{background-color:#D7D7D7;}

.right_div{margin:7px 20px 10px 20px;border:1px solid #666666;z-index:100;}

#user_div{display:none;}

#have_role_div_span{font-size:14px;font-weight:bold;padding:5px;margin-top:10px;}
.have_role_table{background-color:#666666;margin-top:5px;font-size:13px;}
.have_role_table td{background-color:#FFFFFF;height:20px;}

button.btu{padding:0px 12px;line-height:25px;margin-right:10px;cursor:pointer;}

.alertBox_text span{font-weight:normal;letter-spacing:0;}
.text_red{color:red;}

</style>

<script type="text/javascript">

var roleNodeChecked = null; //角色数选择的节点
//var departmentList = ${departmentList}; //部门
var roleList = null; //角色
var roleObj = {}; //角色

$(function(){
	
	//弹出框扩展
	layer.config({
	    extend: 'extend/layer.ext.js'
	}); 
	
	//获得所有角色
	getAllRole();
	
	//获取所有权限页面
	getAllPage();
	
	//tab的动作
	$(".tab_span").click(function(){
		if($(this).hasClass("tab_span_checked")){
			//alert("self checked");
		}else{
			//去除颜色
			$(".tab_span").removeClass("tab_span_checked");
			//加上颜色
			$(this).addClass("tab_span_checked");
			
			if($(this).attr("role") == "role"){
				$("#user_div").hide();
				$("#role_div").show();
			}else{
				$("#role_div").hide();
				$("#user_div").show();
				if(roleNodeChecked != null){
					//roleNodeChecked.id = 0;
					roleUserTable(roleNodeChecked.id);
				}
					
			}
		}
	});
	
	
	$("#table_div").width($("#role_div").width());
});

function getAllRole(){
	//获得所有角色
	//alert(1111111);
	$.ajax({
		type:"POST",
		async:true,  //默认true,异步
		url:"${bathPath}/aDKManageRole/getAllManageRole.action",
		success:function(data){
			//所有角色
			roleList = data;
			
			$.each(roleList, function(index, val){
				roleObj[val.id+''] = val.name;
			});
			
			var setting = {
					view: {
						selectedMulti: false
					},
					callback: {
						beforeClick: function(treeId, treeNode, clickFlag){
							if(!treeNode.id){
								return false;
							}
						},
						onClick: function(e, treeId, treeNode, clickFlag){
							//alert(1);
							roleNodeChecked = treeNode;
							//把右边的选中
							$.ajax({
								type:"POST",
								async:true,  //默认true,异步
								data:"roleId="+roleNodeChecked.id,
								url:"${bathPath}/aDKManageRole/getManagePageByRole.action",
								success:function(data){
									
									var treeObj = $.fn.zTree.getZTreeObj("treePage");
									
									//取消勾选
									$.each(treeObj.getCheckedNodes(true), function(index, val){
										treeObj.checkNode(val, false, true);
									});
									
									var haveData = [];
									$.each(data, function(index, val){
										//alert(JSON.stringify(val));
										if(val.parentId){
											//alert(JSON.stringify(treeObj.getNodeByTId(val.id+"")));
											haveData.push(treeObj.getNodeByParam("id", val.id, null));	
										}
									});
									//alert(JSON.stringify(haveData.length));
									
									//给权限表格加上数据
									//$("#have_role_div_span").text(roleNodeChecked.name+"拥有的权限：");
									
									for (var i=0; i < haveData.length; i++) {
										if(haveData[i].levelType == 1){
											treeObj.checkNode(haveData[i], true, true);
										}
									}
								}
							});
							//角色成员
							roleUserTable(roleNodeChecked.id);
						}
					}
			};
			var zNodes =[{name:"角色列表", open:true, children:null}];
			zNodes[0].children = data;
			$.fn.zTree.init($("#treeDemo"), setting, zNodes);
	    }
	});
}

function getAllPage(){
	//获取所有权限页面
	$.ajax({
		type:"POST",
		async:true,  //默认true,异步
		url:"${bathPath}/aDKManageRole/getAllManagePage.action",
		success:function(data){
			
			//打开
			$.each(data, function(index, val){
				val.open = true;
				
				//权限表格
				var trHtml = "<tr index='"+val.id+"' align='center' valign='middle' style='display:none;'><td class='index'>"+(index+1)+"</td><td class='roleName'>"+val.name+"</td></tr>";
				$(".have_role_table").append(trHtml);
			});
			
			var setting = {
					data: {
						key: {
							url: "xUrl"
						},
						simpleData: {
							enable: true,
							pIdKey: "parentId"
						}
					},
					check: {
						enable: true
					},
					callback: {
						beforeClick: function(treeId, treeNode, clickFlag){
							return false;
						}
					}
			};
			$.fn.zTree.init($("#treePage"), setting, data);
	    }
	});
}

//增加权限
function addRow(oldId, oldName, updateUrl){
	
	//$("#BlackBox_backVal").val("");
	
	//oldId, oldName, updateUrl 有值，说明是修改
	
	//去除验证格式
	$("#role_add_div").find("input").val("");
   	$("#role_add_div").find("div").last().hide();
   	$("#role_add_div").find("span").removeClass("text_red");
   	
   	var indexTitle = "增加角色";
   	if(updateUrl){
   		indexTitle = "修改角色";
   		$("#role_add_div").find("input").val(oldName);
   	}
	
	layer.open({
	    type: 1,
		title: indexTitle,
	    area: ['360px', '230px'], //宽高
	    content: $("#role_add_div"),
	    btn: ['保存','关闭'], //按钮
	    yes: function(index, layero){
	    	
	    	var newRoleNameCheckFlag = true;
	    	
	    	var newRoleName = $.trim($("#role_add_div").find("input").val());
	    	
	    	if(newRoleName == ""){
	    		$("#role_add_div").find("div").last().text("角色不可为空").show();
				newRoleNameCheckFlag = false;
	    	}
	    	
	        //验证名称是否重复
	    	for(var i=0; i<roleList.length; i++){
    			if(newRoleName == roleList[i].name && (oldName && oldName != newRoleName)){
    				$("#role_add_div").find("div").last().text("此角色已经存在").show();
    				newRoleNameCheckFlag = false;
    				break;
    			}
    		}
    		
	        //长度最多10个字符
    		if(newRoleName.length > 10){
    			$("#role_add_div").find("span").addClass("text_red");
    			return false;
    		}else{
    			$("#role_add_div").find("span").removeClass("text_red");
    		}
	        
	        if(newRoleNameCheckFlag){
	        	//验证通过
	        	$("#role_add_div").find("div").last().hide();
	        	
	        	var paramUrl = "${bathPath}/aDKManageRole/addManageRole.action";
	        	var paramData = "name="+newRoleName;
	        	if(updateUrl){
	        		paramUrl = updateUrl;
	        		paramData = "name="+newRoleName+"&id="+oldId;
	        	}
	        	
	        	//保存
	        	$.ajax({
	        		type:"POST",
	        		async:true,  //默认true,异步
	        		url: paramUrl,
	        		data: paramData,
	        		success:function(){
	        			//获得所有角色
	        			getAllRole();
	        			
	        			layer.close(index);
	        	    }
	        	});
	        }
	    }
	});

}

//删除权限
function deleteRow(){
	
	if(roleNodeChecked){
		
		Dialog.confirm('确认删除吗？', function(){
	    	
	    	$.ajax({
	    		type:"POST",
	    		async:true,  //默认true,异步
	    		url:"${bathPath}/aDKManageRole/delManageRole.action",
	    		data:"id="+roleNodeChecked.id,
	    		success:function(data){
	    			
	    			if(data == "SUCCESS"){
	    				
	    				Dialog.alert('删除成功！', function(indexOk){
	    					getAllRole();
	    					Dialog.close();
	       				});
	    				
	    			}else{
	    				Dialog.alert('删除失败！');
	    			}
	    	    }
	    	});
		});
		
	}else{
		layer.alert("<div class='alertBox_text'>请先选择一个角色！</div>");
	}
	
}

//修改权限
function editRow(){
	if(roleNodeChecked){
		
		addRow(roleNodeChecked.id, roleNodeChecked.name, "${bathPath}/aDKManageRole/updateManageRole.action");

	}else{
		layer.alert("<div class='alertBox_text'>请先选择一个角色！</div>");
	}
}

//保存角色的权限页面
function saveRolePage(){
	
	if(roleNodeChecked){
		
layer.confirm('确认保存吗？', {icon: 3, title:'提示'}, function(index){
	    	
			var layerSaving = layer.msg('保存中...', {icon: 16, time: 0, shade: [0.3, '#000']});
			
			var treeObj = $.fn.zTree.getZTreeObj("treePage");
			
			//增加现在选择的节点
			var param = [];
			
			param.push({"name":"roleId", "value":roleNodeChecked.id});
			
			$.each(treeObj.getCheckedNodes(true), function(index, val){
				param.push({"name":"pageIds", "value":val.id});
			});
			//alert(JSON.stringify(param));
			$.ajax({
				type:"POST",
				async:true,  //默认true,异步
				url:"${bathPath}/aDKManageRole/addManagePageByRole.action",
				data:param,
				success:function(data){
					
					layer.close(layerSaving);
					
					if(data == "SUCCESS"){
	    				layer.alert('保存成功！', {icon: 1});
	    			}else{
	    				layer.alert('保存失败！', {icon: 0});
	    			}
			    }
			});
			
		});
		
	}else{
		layer.alert("请先选择一个角色，并勾选这个角色可以拥有的权限！");
	}
}

//角色成员
function roleUserTable(roleId){
	//alert(roleId);
	if($('#exampleTable').html() != ""){
		//表格已经存在
		var param = new Object();
		param.roleId = roleId;
		param.page = 1;
		//alert(JSON.stringify(param));
		$('#exampleTable').mmGrid().load(param);
	}else{
		//表格
		//alert(roleId);
		$('#exampleTable').mmGrid({
	    	root:'rows',
			url:"${bathPath}/aDKManageUser/selectCll.action",
			params:{"roleId": roleId},
	    	width: 'auto',
	    	height: 'auto',
	        //checkCol: true,
	        fullWidthRows: true, //表格第一次加载数据时列伸展，自动充满表格
    		showBackboard: false,
	        //nowrap: true,
	        indexCol: true,  //索引列
	        cols: [{title: 'ID', name: 'id', width:60, hidden:true},
				   {title: '姓名', name: 'realName', width:70},
				   {title: '账号', name: 'userName', width:100},
				   {title: '性别', name: 'gender', width:70, renderer:function(val, item, rowIndex){
					   if(val == 0){
						   return "男";
					   }else if(val == 1){
						   return "女";
					   }
				   }},
				   {title: '角色', name: 'roleIdList', width:200, renderer:function(val, item, rowIndex){
					   // alert(JSON.stringify(roleList));
					   var role = "";
					   for(var i=0; i<val.length; i++){
						   role = role + roleObj[val[i]+""] + ",";
					   }
					   role = role.substring(0, role.length-1);
					   return "<label title='"+role+"'>"+role+"</label>";
				   }},
				   {title: '操作', name: 'id', width:47, renderer:function(val, item, rowIndex){
					   // alert(JSON.stringify(roleList));
					   return "<a href='javascript:;' onclick='removeRole("+val+", "+rowIndex+")'>删除</a>";
				   }}
	           ],
	        plugins : [
	        	$('#paginator11-1').mmPaginator({
	        		totalCountName: 'total',   //对应MMGridPageVoBean count
	        		page: 1,                   //初始页
	        		pageParamName: 'page',     //当前页数
	        		limitParamName: 'pageSize', //每页数量
	        		limitList: [10, 20, 40, 50]
	        	})
	        ]
	    });	
	}
}

//选择用户
function alertWinUser(){
	
	if(roleNodeChecked == null){
		//未选择角色
		layer.alert("请先选择一个角色！");
	}else{
		
		layer.open({
		    type: 2,
		    title: '选择用户',
		    area: ['800px', '460px'],
		    content: '${bathPath}/aDKManageRole/selectUser.action?roleId='+roleNodeChecked.id       //iframe的url
		});
	}
}

//保存完用户的角色
function afterSaveUserRole(){
	//关闭弹出框
	layer.closeAll();
	//刷新表格
	roleUserTable(roleNodeChecked.id);
}

//删除用户的角色
	function removeRole(id, rowIndex){
		layer.confirm('确认删除吗？', {icon: 3, title:'提示'}, function(index){
			var layerSaving = layer.msg('保存中...', {icon: 16, time: 0, shade: [0.3, '#000']});
			$('#exampleTable').mmGrid().removeRow(rowIndex);
		$.ajax({
			type:"POST",
			async:true,  //默认true,异步
			url:"${bathPath}/aDKManageRole/deleteUserRole.action",
			data:"userId="+id+"&roleId="+roleNodeChecked.id,
			success:function(data){
				
				layer.close(layerSaving);
				
				//刷新表格
				var param = new Object();
				param.roleId = roleNodeChecked.id;
				$('#exampleTable').mmGrid().load(param);
		    }
		});	
		
	});
}

function key_down(num) {
	if (num == 13) {
		saveRolePage();
	}
}
</script>
</head>
<style type="text/css"> 
.layui-table-cell .layui-form-checkbox[lay-skin="primary"]{
     top: 50%;
     transform: translateY(-50%);
}
</style>
<body >
<div class="layui-tab" lay-filter="demo" lay-allowclose="true" style="margin-left:15px; height: 450px; width: 900px;">
	<ul class="layui-tab-title" >
    <li lay-id="22">角色管理</li>
  </ul> 
	<div class="layui-tab-content" style="height: 600px; width: 900px">
    <div class="layui-tab-item layui-show" >
  <form id="myform" class="layui-form layui-form-pane">
 <div class="demoTable" style="margin-top: 20px;margin-left:25px;"> 
</div> 
</form>   
</div>
<table class="layui-hide"  id="demo"></table>
<table class="layui-hide"  id="test"  lay-filter="test"></table>
	<div class="first_div" style="border-right:none;border-bottom:none;border-left:none;padding:10px 20px 20px 20px;height:450px" >
		
		<table class="tree_table" cellpadding="0" cellspacing="0" >
			<tr>
				<td class="left_tree" valign="top">
					
					<!-- 按钮 -->
					<table class="png_table" cellpadding="0" cellspacing="0" style="margin-top: 5px;">
						<tr>
							<td>
								<button class="btu_0" onclick="addRow()" style="margin:0px 10px 0px 10px;line-height: 16px;">增加</button>
							</td>
							<td>
								<button class="btu_0" onclick="deleteRow()" style="margin:0px 10px 0px 0px;line-height: 16px;">删除</button>
							</td>
							<td>
								<button class="btu_0" onclick="editRow()" style="margin:0px 10px 0px 0px;line-height: 16px;">修改</button>
							</td>
						</tr>
					</table>
				
					<ul id="treeDemo" class="ztree"></ul>
				</td>
				<td>
					<div style="margin-top:20px;">
						<span class="tab_span tab_span_checked" role="role">角色权限</span>
						<span class="tab_span" style="margin-left:10px;" role="user">角色成员</span>
						<div class="right_div" id="role_div" align="right" >
							<table style="width:100%;height:100%;" cellpadding="0" cellspacing="0" >
								<tr align="left" valign="top">
									<td style="width:300px;">
										<ul id="treePage" class="ztree" style=""></ul>
									</td>
									<td>
										<div class="have_role_div">
											<div id="have_role_div_span"></div>
											<table class="have_role_table" cellpadding="1" cellspacing="1" style="display:none;">
												<tr align="center" valign="middle">
													<td style="width:60px;font-weight:bold;background-color:#DDDDDD;">序号</td>
													<td style="width:180px;font-weight:bold;background-color:#DDDDDD;">权限名称</td>
												</tr>
											</table>
										</div>	
									</td>
								</tr>
							</table>
							<button class="btu_0" style="margin-bottom:10px;margin-right:10px;" onclick="saveRolePage()">保存</button>
						</div>
						<div class="right_div" id="user_div">
							<!-- 角色成员 -->
							<div style="margin:10px;" id="table_div">
								<button class="btu_0" onclick="alertWinUser()" style="margin-bottom:5px;line-height: 16px;">增加用户</button>
								<table id="exampleTable"></table>
								<div style="text-align:right;">
							    	<div id="paginator11-1"></div>
							    </div>
							</div>
						</div>
					</div>
				</td>
			</tr>
		</table>
	</div>
	
	<input type="hidden" id="BlackBox_backVal" />
	
	<div id="role_add_div" style="padding:10px;padding-left:20px;display:none;" >
		<div style="font-size:14px;line-height:40px;">请输入新角色的名称(<span>名称最多10个字符</span>)</div>
		<input type="text" id="role_name" name="role_name" class="input_0" style="width:240px;" />
		<div style="font-size:14px;line-height:40px;color:red;display:none;">此角色已经存在</div>
	</div>
	</div>
	</div>
</body>
</html>